<?php
namespace app\tools\logic;
use think\facade\Db;

class LoginLogic{
	//开始登录
	static function toLogin(){
		$username = input('username','');
		$password = input('password','');
		if(!$username){
			return ['code'=>104];
		}
		if(!$password){
			return ['code'=>105];
		}
		//查询数据库
		$info = Db::name('auth_user')
				->where('user_name', $username)
				->whereOr('phone', $username)
				->find();
		if(!$info){
			return ['code'=>106];
		}elseif($info['status']!=1){
			return ['code'=>107];
		}

		$cof = config('app');
		$error_lock_open = $cof['error_lock_open'];
		$error_number = $cof['error_number'];
		$error_time = $cof['error_time'];
		$is_lock = 0;

		if($error_lock_open && $info['is_lock']==1){
			if((time()-strtotime($info['err_time']))/60<$error_time){
				return ['code'=>108];
			}
		}
		// echo (time()-strtotime($info['err_time']))/60;exit;

		//密码验证
		if($info['password']!=md5(md5($password).$info['salt'])){
			if(!$error_lock_open){
				return ['code'=>109];
			}
			//设置错误信息，以及是否需要 锁定账户
			$data = [];
			if($info['err_time'] && time()-strtotime($info['err_time'])>30*60){
				//首选判断时间是否已经超过24小时，如果超过24小时，则重置
				$data['err_times'] = 1;
				$data['is_lock'] = 0;
			}else{
				$data['err_times'] = $info['err_times']+1;
			}
			//错误时间记录
			$data['err_time'] = date('Y-m-d H:i:s');
			if($data['err_times']>=$error_number){
				$data['is_lock'] =	$is_lock  = 1;
			}
			// print_r($data);
			Db::name('auth_user')
				->where('id', $info['id'])
				->update($data);
			if($is_lock==1){
				return ['code'=>108];
			}else{
				return ['code'=>109];
			}

		}
		//密码正确，正常登录
		$token = createToken(64);
		$data = [];
		$data['err_times'] = 0;
		$data['is_lock'] = 0;
		$data['token'] = $token;
		$data['token_exp'] = date('Y-m-d H:i:s', time()+2*60*60); //过期时间
		Db::name('auth_user')
				->where('id', $info['id'])
				->update($data);
		//登录成功了，写入token值
		return ['code'=>0,'data'=>['token'=>$token,'token_exp'=>$data['token_exp']]];
	}

}